package com.example.demo.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;

import com.example.demo.common.StringUtils;

public class ShiroSimpleSessionManager extends  DefaultWebSessionManager {

	private static final String TOKEN="jwt_token";
	
	private static String corsSessionId="cors_jsessionid";
	private static boolean enableCorsSession = true; //session 共享
	
	@Value("${demo-settings.EnableCorsSession}")
	public void setEnableCorsSession(boolean enableCorsSessionValue) {
		enableCorsSession=enableCorsSessionValue;
	}
	
	public ShiroSimpleSessionManager() {
		super();
	}
	
	/**
	 * 重写SessionId sessionId 跨域
	 */
	@Override
	public Serializable getSessionId(ServletRequest request, ServletResponse response) {
		  
		HttpServletRequest httpRequest=(HttpServletRequest)request;
		HttpServletResponse httpResponse=(HttpServletResponse)response;		
		
		//使用跨域SESSION 时 
		if(enableCorsSession) {
			String sessionId=httpRequest.getHeader(corsSessionId);
			if(!StringUtils.IsNullOrEmpty(sessionId)) {			  
				httpResponse.setHeader(corsSessionId, sessionId);			
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			}
			request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, isSessionIdUrlRewritingEnabled());
		}
		
		String token=httpRequest.getHeader(TOKEN);
		httpResponse.setHeader(TOKEN, token);
		
		return super.getSessionId(request,response);		
	}
	
}
